const jwt = require("jsonwebtoken");

const { JWT_SECRET } = require("../config/config.default");

const {
    tokenExpiredError,
    invalidToken,
    hasNotAdminPermission,
} = require("../constant/err.type");

const auth = async (ctx, next) => {
    const { authorization = '' } = ctx.request.header;
    
    try {
        const token = authorization.replace("Bearer ", "");
        console.log(token);
        //user包含payload中的id, username，is_admin
        const user = jwt.verify(token, JWT_SECRET);
        ctx.state.user = user;
    } catch (error) {
        switch (error.name) {
            case "TokenExpiredError":
                console.error("token过期", error);
                return ctx.app.emit("error", tokenExpiredError, ctx);
            case "JsonWebTokenError":
                console.error("无效的token", error);
                return ctx.app.emit("error", invalidToken, ctx);
            default:
                console.error("token校验，其他错误", error);
        }
    }

    await next();
};

const hadAdminPermission = async (ctx, next) => {
    const { is_admin } = ctx.state.user;
    if (!is_admin) {
        console.error("用户没有管理员权限", ctx.state.user);
        return ctx.app.emit("error", hasNotAdminPermission, ctx);
    }

    await next()
};

module.exports = {
    auth,
    hadAdminPermission
};
